package com.example.hdz.floatwindowdemo;

import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.view.KeyEvent;

/**
 * @author hdz
 * @date 2019/08/05
 */
public class Util {


    public static void musicNext(Context context) {
        musicOpt(context, KeyEvent.KEYCODE_MEDIA_NEXT);
    }
    public static void musicPrevious(Context context) {
        musicOpt(context, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
    }
    public static void musicPlayOrPause(Context context) {
        musicOpt(context, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
    }

    private static void musicOpt(Context context, int code) {
        long now = SystemClock.uptimeMillis();

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MEDIA_BUTTON);
        KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, down);
        context.sendBroadcast(intent);

        Intent intent2 = new Intent();
        intent2.setAction(Intent.ACTION_MEDIA_BUTTON);
        KeyEvent up = new KeyEvent(now, SystemClock.uptimeMillis(), KeyEvent.ACTION_UP, code, 0);
        intent2.putExtra(Intent.EXTRA_KEY_EVENT, up);
        context.sendBroadcast(intent2);
    }
}
